/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.persistence.entity;

import com.je.bpm.engine.delegate.event.ActivitiEventDispatcher;
import com.je.bpm.engine.delegate.event.ActivitiEventType;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.persistence.AbstractManager;
import com.je.bpm.engine.impl.persistence.CountingExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.data.DataManager;

public abstract class AbstractEntityManager<EntityImpl extends Entity> extends AbstractManager implements EntityManager<EntityImpl> {

    public AbstractEntityManager(ProcessEngineConfigurationImpl processEngineConfiguration) {
        super(processEngineConfiguration);
    }

    /*
     * CRUD operations
     */


    @Override
    public EntityImpl findById(String entityId) {
        return getDataManager().findById(entityId);
    }

    @Override
    public EntityImpl create() {
        return getDataManager().create();
    }

    @Override
    public void insert(EntityImpl entity) {
        insert(entity, true);
    }

    @Override
    public void insert(EntityImpl entity, boolean fireCreateEvent) {
        getDataManager().insert(entity);
        ActivitiEventDispatcher eventDispatcher = getEventDispatcher();
        if (fireCreateEvent && eventDispatcher.isEnabled()) {
            eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, entity));
            eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, entity));
        }
    }

    @Override
    public EntityImpl update(EntityImpl entity) {
        return update(entity, true);
    }

    @Override
    public EntityImpl update(EntityImpl entity, boolean fireUpdateEvent) {
        EntityImpl updatedEntity = getDataManager().update(entity);
        if (fireUpdateEvent && getEventDispatcher().isEnabled()) {
            getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, entity));
        }
        return updatedEntity;
    }

    @Override
    public void delete(String id) {
        EntityImpl entity = findById(id);
        delete(entity);
    }

    @Override
    public void delete(EntityImpl entity) {
        delete(entity, true);
    }

    @Override
    public void delete(EntityImpl entity, boolean fireDeleteEvent) {
        getDataManager().delete(entity);
        if (fireDeleteEvent && getEventDispatcher().isEnabled()) {
            getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, entity));
        }
    }

    protected abstract DataManager<EntityImpl> getDataManager();

    /* Execution related entity count methods */

    protected boolean isExecutionRelatedEntityCountEnabledGlobally() {
        return processEngineConfiguration.getPerformanceSettings().isEnableExecutionRelationshipCounts();
    }

    protected boolean isExecutionRelatedEntityCountEnabled(ExecutionEntity executionEntity) {
        if (executionEntity instanceof CountingExecutionEntity) {
            return isExecutionRelatedEntityCountEnabled((CountingExecutionEntity) executionEntity);
        }
        return false;
    }

    protected boolean isExecutionRelatedEntityCountEnabled(CountingExecutionEntity executionEntity) {

        /*
         * There are two flags here: a global flag and a flag on the execution entity.
         * The global flag can be switched on and off between different reboots,
         * however the flag on the executionEntity refers to the state at that particular moment.
         *
         * Global flag / ExecutionEntity flag : result
         *
         * T / T : T (all true, regular mode with flags enabled)
         * T / F : F (global is true, but execution was of a time when it was disabled, thus treating it as disabled)
         * F / T : F (execution was of time when counting was done. But this is overruled by the global flag and thus the queries will be done)
         * F / F : F (all disabled)
         *
         * From this table it is clear that only when both are true, the result should be true,
         * which is the regular AND rule for booleans.
         */

        return isExecutionRelatedEntityCountEnabledGlobally() && executionEntity.isCountEnabled();
    }


}
